package com.css.dzj.dzjportal.modules.apunitinfo;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.css.dzj.dzjportal.common.util.R;
import com.css.dzj.dzjportal.common.util.excel.ExcelData;
import com.css.dzj.dzjportal.common.util.excel.ExportExcelUtils;
import com.css.dzj.dzjportal.common.util.http.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.util.StringUtils;
import com.css.dzj.dzjportal.common.util.ServiceUtil;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 监管对象库: 安评单位信息的查询
 */
@RestController
@RequestMapping("/apUnitInfo")
@PropertySource(value = "classpath:base.properties")
public class ApUnitController {
    @Value("${AP_URL}")
    private String apURL;
    @Value("${XCJY_URL}")
    private String xcjyURL;
    @Autowired
    private HttpServletRequest request;

    /**
     * @param year
     * @return
     */
    @GetMapping("/map")
    public R getTotalByYear(String year) {
        String[] mapPro = new String[]{"南海诸岛", "北京", "天津", "上海", "重庆", "河北", "河南", "云南", "辽宁", "黑龙江", "湖南", "安徽", "山东", "新疆", "江苏", "浙江", "江西", "湖北", "广西", "甘肃", "山西", "内蒙古", "陕西", "吉林", "福建", "贵州", "广东", "青海", "西藏", "四川", "宁夏", "海南", "台湾", "香港", "澳门"};
        /***
         * 获取检查行为
         */
        String msg = HttpClientUtil.doGet(apURL + "/check/countbyyear?year=" + year);
        JSONObject jsonObject = JSON.parseObject(msg);
        Map<String, Object> mapCheck = new HashMap<>();
        if(!StringUtils.isEmpty(msg)){
            Object count = jsonObject.get("count");
            mapCheck = JSONObject.parseObject(count.toString());
        }
        /**
         * 获取处罚行为
         */
        String msgPunish = HttpClientUtil.doGet(apURL + "/punish/punishyear?year=" + year);
        JSONObject jsonPunish = JSON.parseObject(msgPunish);
        Map<String, Object> mapPunish = new HashMap<>();
        if(!StringUtils.isEmpty(msgPunish)) {
            Object punishOb = jsonPunish.get("count");
            mapPunish = JSONObject.parseObject(punishOb.toString());
        }

        /**
         * 获取强制行为
         */
        String msgForce = HttpClientUtil.doGet(apURL + "/force/forceyear?year=" + year);
        JSONObject jsonForce = JSON.parseObject(msgForce);
        Map<String, Object> mapForce = new HashMap<>();
        if(!StringUtils.isEmpty(msgForce)) {
            Object  forceOb = jsonForce.get("count");
            mapForce = JSONObject.parseObject(forceOb.toString());
        }

        /**
         * 获取其他行为
         */
        String msgOther = HttpClientUtil.doGet(apURL + "/other/otheryear?year=" + year);
        JSONObject jsonOther = JSON.parseObject(msgOther);
        Map<String, Object> mapOther = new HashMap<>();
        if(!StringUtils.isEmpty(msgOther)) {
            Object otherOb = jsonOther.get("count");
            mapOther = JSONObject.parseObject(otherOb.toString());
        }


        /**
         * 获取建设单位
         */
        String msgCon = HttpClientUtil.doGet(apURL + "/constr/countconstryear?year=" + year);
        JSONObject jsonCon = JSON.parseObject(msgCon);
        Map<String, Object> mapCon = new HashMap<>();
        if(!StringUtils.isEmpty(msgCon)) {
            Object constr = jsonCon.get("count");
            mapCon = JSONObject.parseObject(constr.toString());
        }
        /**
         * 获取安评单位
         */
        String msgUnit = HttpClientUtil.doGet(apURL + "/evalunit/countunityear?year=" + year);
        JSONObject jsonUnit = JSON.parseObject(msgUnit);
        Map<String, Object> mapUnit = new HashMap<>();
        if(!StringUtils.isEmpty(msgUnit)) {
            Object unit = jsonUnit.get("count");
            mapUnit = JSONObject.parseObject(unit.toString());
        }

        /**
         * 获取宣传教育材料上传数量
         */
        String orgName = ServiceUtil.getOrgName(request);
        if(StringUtils.isEmpty(orgName)) {
            return R.error("登录人所属机构不能为空");
        }
        orgName = orgName.replace("地震局", "");
        // String eduMsg = HttpClientUtil.doGet(xcjyURL + "/material/mapCountByYearAndOrgName?year=" + year + "&orgName=" + orgName);
        String eduMsg = HttpClientUtil.doGet(xcjyURL + "/material/countSpByYear?year=" + year);
        Map<String, Object> eduMap = new HashMap<>();
        if(!StringUtils.isEmpty(eduMsg)) {
            JSONObject jsonEdu = JSON.parseObject(eduMsg);
            Object eduData = jsonEdu.get("data");
            eduMap = JSONObject.parseObject(eduData.toString());
        }
        //宣传教育材料数量为edunum
        //1.遍历四个行为信息，去重、汇总
        List<Map<String, Object>> actList = new ArrayList();
        actList.add(mapCheck);
        actList.add(mapPunish);
        actList.add(mapForce);
        actList.add(mapOther);
        Map<String, Object> mapAllAct = new HashMap<>();
        if(!actList.isEmpty()){
            for (Map<String, Object> map : actList) {
                for (Map.Entry<String, Object> entry : map.entrySet()) {
                    String key = entry.getKey();
                    Integer value = (Integer) entry.getValue();
                    Integer valueAll = (Integer) mapAllAct.get(entry.getKey());
                    if (valueAll == null) {
                        mapAllAct.put(key, value);
                    } else {
                        valueAll = valueAll.intValue() + value.intValue();
                        mapAllAct.put(key, valueAll);
                    }
                }
            }
        }
        List<Map<String, Object>> listNewDate1 = new ArrayList();
        Integer actnum = 0;
        for (Map.Entry<String, Object> entry : mapAllAct.entrySet()) {
            HashMap map = new HashMap();
            String name = entry.getKey();
            if(!name.equals("totalsize")) {
                Integer value = (Integer) entry.getValue();
                actnum += value;
                map.put("name", name);
                map.put("value", value);
                listNewDate1.add(map);
            }
        }
        //2.遍历两个单位信息汇总
        List<Map<String, Object>> unitList = new ArrayList();
        unitList.add(mapCon);
        unitList.add(mapUnit);
        Map<String, Object> mapAllUnit = new HashMap<>();
        if(!unitList.isEmpty()){
            for (Map<String, Object> map : unitList) {
                for (Map.Entry<String, Object> entry : map.entrySet()) {
                    String key = entry.getKey();
                    Integer value = (Integer) entry.getValue();
                    Integer valueAll = (Integer) mapAllUnit.get(entry.getKey());
                    if (valueAll == null) {
                        mapAllUnit.put(key, value);
                    } else {
                        valueAll = valueAll.intValue() + value.intValue();
                        mapAllUnit.put(key, valueAll);
                    }
                }
            }
        }

        List<Map<String, Object>> listNewDate2 = new ArrayList();
        Integer unitNum = 0;
        //初始化单位数量
        for (Map.Entry<String, Object> entry : mapAllUnit.entrySet()) {
            HashMap map = new HashMap();
            String name = entry.getKey();
            if(!name.equals("totalsize")) {
                Integer value = (Integer) entry.getValue();
                unitNum += value;
                map.put("name", name);
                map.put("unitValue", value);
                listNewDate2.add(map);
            }
        }
        //3.遍历宣传教育信息汇总
        List<Map<String, Object>> eduList = new ArrayList();
        eduList.add(eduMap);
        Map<String, Object> mapAllEdu = new HashMap<>();
        if(!eduList.isEmpty()){
            for (Map<String, Object> map : eduList) {
                for (Map.Entry<String, Object> entry : map.entrySet()) {
                    String key = entry.getKey();
                    Integer value = (Integer) entry.getValue();
                    Integer valueAll = (Integer) mapAllEdu.get(entry.getKey());
                    if (valueAll == null) {
                        mapAllEdu.put(key, value);
                    } else {
                        valueAll = valueAll.intValue() + value.intValue();
                        mapAllEdu.put(key, valueAll);
                    }
                }
            }
        }
        List<Map<String, Object>> listNewDate3 = new ArrayList();
        Integer eduNum = 0;
        for (Map.Entry<String, Object> entry : mapAllEdu.entrySet()) {
            HashMap map = new HashMap();
            String name = entry.getKey();
            if(!name.equals("totalsize")) {
                Integer value = (Integer) entry.getValue();
                eduNum += value;
                map.put("name", name);
                map.put("eduValue", value);
                listNewDate3.add(map);
            }
        }

        List<Map<String, Object>> listForDate = new ArrayList();
        //遍历城市信息添加行为、单位、宣传教育数据数量
        for(String arr:mapPro){
            //遍历行为数据
            HashMap mapNew1=new HashMap();
            //首部初始化该城市的信息
            mapNew1.put("name",arr);
            mapNew1.put("value",0);
            int originum = 0;
            for (Map map:listNewDate1) {
                String str=(String)map.get("name");
                //消除空数据对contains方法的影响
                if(str.length()>0) {
                    int nownum;
                    nownum = (Integer) map.get("value");
                    if(str.length()>1) {
                        //数据截取，标准化数据，使得与mapPro的格式对应
                        String sTr = str.substring(0,2);
                        if (arr.contains(sTr)) {
                            originum = nownum + originum;
                            mapNew1.put("value", originum);
                        }
                    }
                }
            }
            //遍历单位数据
            mapNew1.put("unitValue",0);
            int origiunitnum = 0;
            for (Map map:listNewDate2) {
                String str=(String)map.get("name");
                if(str.length()>0){
                    int nownum;
                    nownum = (Integer)map.get("unitValue");
                    if(str.length()>1) {
                        String sTr = str.substring(0,2);
                        if(arr.contains(sTr)){
                            origiunitnum  = nownum +origiunitnum;
                            mapNew1.put("unitValue",origiunitnum);
                        }
                    }

                }
            }
            //遍历宣传教育数据
            mapNew1.put("eduValue",0);
            int origiedunum = 0;
            for (Map map:listNewDate3) {
                String str=(String)map.get("name");
                if(str.length()>0) {
                    int nownum;
                    nownum = (Integer) map.get("eduValue");
                    if(str.length()>1) {
                        String sTr = str.substring(0, 2);
                        if (arr.contains(sTr)) {
                            origiedunum = nownum + origiedunum;
                            mapNew1.put("eduValue", origiedunum);
                        }
                    }

                }
            }
            listForDate.add(mapNew1);
        }
        String wholeData = JSON.toJSONString(listForDate);
        return R.ok().put("data", listForDate).put("acttotalnum",actnum).put("unittotalnum",unitNum).put("edunum",eduNum);
    }

    @GetMapping("/getApUnitInfo")
    public R getApUnitInfo(@RequestParam Integer pageNo, @RequestParam Integer pageSize,
                           @RequestParam(name = "unitName", required = false) String unitName,
                           @RequestParam(name = "uniscid", required = false) String uniscid,
                           @RequestParam(name = "startTime", required = false) String startTime,
                           @RequestParam(name = "endTime", required = false) String endTime,
                           @RequestParam(name = "spStatus", required = false) String spStatus,
                           @RequestParam(name = "spPerson", required = false) String spPerson,
                           @RequestParam(name = "sbStatus", required = false) String sbStatus) {
        try {
            HashMap params = new HashMap<String, Object>();
            params.put("pageNo", pageNo.toString());
            params.put("pageSize", pageSize.toString());
            params.put("unitName", unitName);
            params.put("uniscid", uniscid);
            params.put("startTime", startTime);
            params.put("endTime", endTime);
            params.put("spStatus", spStatus);
            params.put("spPerson", spPerson);
            params.put("sbStatus", sbStatus);
            String result = HttpClientUtil.doGet(apURL + "/evalunit/getPage", params);
            JSONObject data = JSON.parseObject(result);
            return R.ok().put("data", data);
        } catch (Exception e) {
            return R.error();
        }
    }

    /**
     * 根据参数查询，全部导出
     *
     * @return
     */
    @GetMapping("/export")
    public R export(HttpServletResponse response,
                    @RequestParam(name = "unitName", required = false) String unitName,
                    @RequestParam(name = "uniscid", required = false) String uniscid,
                    @RequestParam(name = "startTime", required = false) String startTime,
                    @RequestParam(name = "endTime", required = false) String endTime,
                    @RequestParam(name = "spStatus", required = false) String spStatus,
                    @RequestParam(name = "spPerson", required = false) String spPerson,
                    @RequestParam(name = "sbStatus", required = false) String sbStatus) {
        try {
            HashMap params = new HashMap<String, Object>();
            params.put("unitName", unitName);
            params.put("uniscid", uniscid);
            params.put("startTime", startTime);
            params.put("endTime", endTime);
            params.put("spStatus", spStatus);
            params.put("spPerson", spPerson);
            params.put("sbStatus", sbStatus);
            String result = HttpClientUtil.doGet(apURL + "/evalunit/getList", params);
            JSONArray jsonApUnits = JSON.parseArray(result);
            // 导出
            export(jsonApUnits, response);
            return R.ok();
        } catch (Exception e) {
            return R.error(e.getMessage());
        }
    }

    /**
     * 选择ids导出数据
     *
     * @param response
     * @param ids
     * @return
     */
    @GetMapping("/exportByIds")
    public R exportMaterialToExcel(HttpServletResponse response, @RequestParam String ids) {
        try {
            HashMap params = new HashMap<String, Object>();
            params.put("ids", ids);
            String result = HttpClientUtil.doGet(apURL + "/evalunit/getListByIds", params);
            JSONArray jsonApUnits = JSON.parseArray(result);
            // 导出
            export(jsonApUnits, response);
            return R.ok();
        } catch (Exception e) {
            return R.error(e.getMessage());
        }
    }

    /**
     * 获取总数
     *
     * @return
     */
    @GetMapping("/getTotalCount")
    public R getTotalCount() {
        try{
            String a = HttpClientUtil.doGet(apURL + "/evalunit/getTotalCount");
            int result = 0;
            if(!StringUtils.isEmpty(a)){
                result = Integer.parseInt(JSON.parse(a).toString());
            }
            return R.ok().put("data", result);
        }catch (Exception e){
            return R.error(e.getMessage());
        }
    }

    /**
     * 导出
     *
     * @param jsonApUnits
     */
    public  void export(JSONArray jsonApUnits, HttpServletResponse response) {
        // 创建导出实体
        ExcelData data = new ExcelData();
        data.setName("安评单位信息表");
        /**
         * 设置Excel标题
         */
        ArrayList<String> titles = new ArrayList<>();
        titles.add("企业名称");
        titles.add("统一社会信用代码");
        titles.add("注册时间");
        titles.add("企业法人");
        data.setTitles(titles);
        /**
         * 处理行数据
         */
        ArrayList<List<Object>> rows = new ArrayList<>();
        for (int i = 0; i < jsonApUnits.size(); i++) {
            ArrayList<Object> row = new ArrayList<>();
            Map<String, Object> eventMap = JSONObject.parseObject(jsonApUnits.get(i).toString());
            row.add(eventMap.get("unitName"));
            row.add(eventMap.get("uniscid"));
            row.add(eventMap.get("establishTime"));
            row.add(eventMap.get("legalMan"));
            rows.add(row);
        }
        data.setRows(rows);
        try {
            // 导出
            ExportExcelUtils.exportExcel(request,response, "安评单位信息表.xlsx", data);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
